<?php
declare(strict_types=1);

namespace Core\Package\ElementPlus\FormCreate;

use Core\HyperfUnit\Response;
use Hyperf\Di\Annotation\Aspect;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Di\Aop\{AbstractAspect, ProceedingJoinPoint};
use Hyperf\Di\Exception\Exception;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;

#[Aspect(priority: 50)]
class FormAspect extends AbstractAspect
{

    #[Inject]
    protected ContainerInterface $container;


    #[Inject]
    protected ServerRequestInterface $request;


    /**
     * 要切入的注解
     * @var array
     */
    public array $annotations = [
        ElemenuForm::class
    ];


    /**
     * @param ProceedingJoinPoint $proceedingJoinPoint
     * @return mixed
     * @throws Exception
     * @author 竹林风@875384189 2021/3/1 11:11
     */
    public function process(ProceedingJoinPoint $proceedingJoinPoint): mixed
    {
        $annotation = $proceedingJoinPoint->getAnnotationMetadata()->method;
        if (isset($annotation[ElemenuForm::class])) {
            /**
             * @var $annotationData ElemenuForm
             */
            $annotationData = $annotation[ElemenuForm::class];
            if (strtoupper($annotationData->method) != $this->request->getMethod()) {
                return $proceedingJoinPoint->process();
            }
            $param = [];
            if (count($annotationData->param) > 0) {
                foreach ($annotationData->param as $key) {
                    $param[] = $this->request->input($key);
                }
            }
            if ($annotationData->class && $annotationData->function) {
                if (!class_exists($annotationData->class)) return Response::Api()->fail('表单不存在');
                if (!method_exists($annotationData->class, $annotationData->function)) return Response::Api()->fail('表单无效');
                /**
                 * @var $form Form
                 */
                $form = call_user_func_array([container($annotationData->class), $annotationData->function], $param);
                if ($form instanceof Form) {
                    return Response::Api()->success(data:$form->toArray());
                }
                return Response::Api()->fail('表单配置错误');
            } elseif ($annotationData->class || $annotationData->function) {
                return Response::Api()->fail('表单配置错误');
            }
        }
        return $proceedingJoinPoint->process();
    }

}
